package com.shihan.service;

import com.shihan.handler.UserServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

/**
 * @Description
 * @Author shihan
 * @Date 2020/8/9 10:27
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    //将来客户端要远程调用的方法
    @Override
    public String sayHello(String msg) {
        String result = "调用成功 -- 客户端请求过来的参数：" + msg;
        System.out.println(result);
        return result;
    }

    //创建一个方法-->启动服务器
    public static void startServer(String ip,int port) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();

        serverBootstrap.group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new UserServerHandler());
                    }
                });

        serverBootstrap.bind(ip,port).sync();
        System.out.println("服务启动");
    }

}
